package com.example.mybatis.demo1.Service;


import com.example.mybatis.demo1.model.User;
import com.example.mybatis.demo1.Mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    public List<User> getAll(){
        return userMapper.getAll();
    }


    //默认返回受影响的行数，添加一条就是返回1
    public int addUser(User user){
        return userMapper.addUser(user);
    }


    // 返回新自增的id
    public int addUser2(User user){
        System.out.println("user1"+user);
        userMapper.addUser2(user);
        System.out.println("user2"+user);
        return user.getId();

        //通过，前后对比，这个user对象前后不一致，真被修改了！，在哪里修改的！
    }



    @Transactional(propagation = Propagation.REQUIRED)
    public int add1(){
        User user = new User();
        user.setUsername("李老四");
        user.setPassword("123");
        user.setPhoto("d:/img/pig.png");
        int ret = userMapper.addUser(user);
        return ret;
    }



    @Transactional(propagation = Propagation.REQUIRED)
    public int add2(){
        User user = new User();
        user.setUsername("李老");
        user.setPassword("123");
        user.setPhoto("d:/img/pig.png");
        int ret = userMapper.addUser(user);
        try {
            int i = 10 / 0;
        } catch (Exception e) {
            //回滚当前事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ret;
    }
}
